package com.bear.richtext.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Movie
import android.os.Build
import android.os.SystemClock
import android.util.AttributeSet
import com.bear.richtext.R
import java.io.InputStream

class GifView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    androidx.appcompat.widget.AppCompatImageView(context, attrs, defStyleAttr) {

    companion object {
        val DEFAULT_DUR = 1000
    }

    constructor(context: Context) : this(context, null, 0)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            setLayerType(LAYER_TYPE_SOFTWARE, null)
        }
        val ta = context.obtainStyledAttributes(attrs, R.styleable.GifView)
        val resourceId = ta.getResourceId(R.styleable.GifView_src, -1)
        setResource(resourceId)
        ta.recycle()
    }

    private var mMovie: Movie? = null
    private var mMovieStart: Long = 0
    private var ratioWidth = 0f
    private var ratioHeight = 0f

    fun setResource(resourceId: Int) {
        if (resourceId == -1) {
            return
        }
        val inputStream = resources.openRawResource(resourceId)
        mMovie = Movie.decodeStream(inputStream)
        requestLayout()
    }

    fun setStream(inputStream: InputStream?) {
        mMovie = Movie.decodeStream(inputStream)
        requestLayout()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mMovie?.let {
            var contentWidth = it.width()
            var contentHeight = it.height()
            contentWidth += paddingLeft + paddingRight
            contentHeight += paddingTop + paddingBottom
            contentWidth = Math.max(contentWidth,suggestedMinimumWidth)
            contentHeight = Math.max(contentHeight,suggestedMinimumHeight)
            var widthSize = resolveSizeAndState(contentWidth,widthMeasureSpec,0)
            var heightSize = resolveSizeAndState(contentHeight,heightMeasureSpec,0)
            ratioWidth = (widthSize / contentWidth).toFloat()
            ratioHeight = (heightSize / contentHeight).toFloat()
            setMeasuredDimension(widthSize,heightSize)

        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val now = SystemClock.uptimeMillis()
        if (mMovieStart == 0L) {
            mMovieStart = now
        }
        mMovie?.let {
            var dur = it.duration()
            if (dur == 0) {
                dur = DEFAULT_DUR
            }
            val relTime = ((now - mMovieStart) % dur).toInt()
            it.setTime(relTime)
            val scale = Math.min(ratioWidth, ratioHeight)
            canvas.scale(scale, scale)
            it.draw(canvas, 0f, 0f)
            invalidate()
        }
    }

}